<template>
  <el-dialog
    :title="$t('message.hykk')"
    :visible.sync="isShow"
    :before-close="closeDrawer"
    width="720px"
  >
    <div>
      <el-form
        ref="form"
        class="doumee-form"
        :rules="rulers"
        :model="param"
        label-width="auto"
        label-suffix="："
        @submit.native.prevent
      >
        <el-form-item :label="$t('message.memberInfo')" prop="memberId">
          <div style="width: 100%">
            <MemberSearch
              ref="memberSearchRef"
              :placeholder="$t('message.hy2')"
              @clear="memberClear"
              @select="memberSelect"
            />
            <div v-if="memberInfo && memberInfo.nickName" class="member_info">
              <div class="item">
                {{ $t("message.name") }}：{{ memberInfo.nickName }}
              </div>
              <div class="item">
                {{ $t("message.sjh") }}：{{ memberInfo.phone }}
              </div>
              <div class="item">
                {{ $t("message.hydj") }}：{{ memberInfo.cardName }}
              </div>
              <div class="item">
                {{ $t("message.czye") }}：<span>{{
                  memberInfo.rechargeMoney || 0
                }}</span>
              </div>
              <div class="item">
                {{ $t("message.zsye") }}：<span>{{
                  memberInfo.giveMoney || 0
                }}</span>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.hydj')" prop="cardTypeId">
          <div class="cart_list">
            <div
              v-for="(item, index) in vipTypes"
              :key="index"
              :class="[index == vipType ? 'select-style' : 'normal-style']"
              class="card-style"
              @click="selectCard(index)"
            >
              <img :src="item.showAvatar" alt="" />
              <div class="card-name">{{ item.cardName }}</div>
              <div class="secondColor">
                {{ $t("message.rmbfh") }}{{ item.price }}
              </div>
            </div>
          </div>
          <div v-if="policyInfo && policyInfo.policyName" class="yhzc">
            {{ $t("message.yhzc") }}：<span>{{ policyInfo.policyName }}</span>
          </div>
        </el-form-item>
        <el-form-item v-if="zsmoney" :label="$t('message.zsje')">
          <el-input
            v-model="param.giveMoney"
            :disabled="!zsmoney"
            placeholder="0.00"
            class="input-with-select w400"
            onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
          />
          <span class="ml10">{{ $t("message.yuan") }}</span>
        </el-form-item>
        <el-form-item>
          <!-- v-if="meta.indexOf('VipAddPay') > -1" -->
          <el-button :loading="xdLoding" type="primary" @click="onSubmit()">{{
            $t("message.qzf")
          }}</el-button>
          <el-button type="primary" @click="memberRegister">{{
            $t("message.zchy2")
          }}</el-button>
          <el-button @click="goBack">{{ $t("message.qx") }}</el-button>
        </el-form-item>
      </el-form>
      <orderDialog
        v-if="isShowOrderModal"
        ref="child"
        @cancelOrder="isShowOrderModal = false"
        @orderSuccess="orderSuccess"
      />
    </div>
  </el-dialog>
</template>

<script>
import store from "@/store";
import orderDialog from "@/components/order";
import {
  cardList,
  memberAdd,
  getPolicyInfo,
  sendSMS,
  memberOrderInfo,
  configList,
} from "@/api";
import MemberSearch from "@/components/MemberSearch";
export default {
  name: "VipAdd",
  components: {
    orderDialog,
    MemberSearch,
  },
  data() {
    return {
      isShowOrderModal: false,
      isShow: false,
      policyInfo: {},
      modalDialog: store.getters.dialog,
      memberInfo: {},
      payLoading: false,
      xdLoding: false,
      meta: [],
      authCode: "",
      swiperOptions: {
        slidesPerView: "auto",
        pagination: {
          el: ".swiper-pagination",
        },
      },
      dialogTableVisible: false,
      zsmoney: false,
      loding: false,
      codeBtnText: this.$t("message.hqyzm"),
      time: 60,
      codeDsiabled: false,
      pwd: null,
      enSurePwd: null,
      firstQueryTime: "",
      vipType: 0,
      vipTypes: [],
      payMoney: "",
      lessMoney: 0.0,
      lastPrice: {},
      param: {
        nickName: null,
        phone: null,
        vcode: null,
        realName: null,
        entityNumber: null,
        sex: "0",
        identityNumber: null,
        payPw: null,
        enSurePwd: null,
        cardTypeId: null,
        venueId: sessionStorage.getItem("venueId"),
      },
      orderInfo: {},
      cardInfo: {},
      rulers: {
        memberId: [
          {
            required: true,
            message: this.$t("message.hy2"),
            trigger: "change",
          },
        ],
        cardTypeId: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.hydj"),
            trigger: "change",
          },
        ],
      },
      faceimg: require("@/icons/png/default_faceid.png"),
    };
  },
  created() {
    this.meta = this.$route.meta.buttons || [];
    this.getCardList();
    configList({ param: { type: "6" } })
      .then((res) => {
        if (res.errorCode !== "000000") return;
        const list = res.recordList;
        const objb = list.find((item) => item.code === "PRESENT_MONEY_CONFIG");
        if (objb && objb.name) {
          this.zsmoney = true;
        }
      })
      .catch((err) => {
        console.log(err);
      });
  },
  methods: {
    goBack() {
      // this.$router.go(-1)
      this.isShow = false;
    },
    getPolicyInfo() {
      if (
        this.vipTypes.length > 0 &&
        this.vipTypes[this.vipType].price &&
        this.memberInfo &&
        this.memberInfo.id
      ) {
        getPolicyInfo({
          param: {
            cardTypeId: this.memberInfo.cardTypeId,
            money: this.vipTypes[this.vipType].price,
            orderType: "05",
          },
        })
          .then((res) => {
            if (res.errorCode === "000000") {
              this.policyInfo = res.record || {};
            } else {
              this.policyInfo = {};
            }
          })
          .catch((_) => {
            this.policyInfo = {};
          });
      } else {
        this.policyInfo = {};
      }
    },
    orderSuccess() {
      this.isShow = false;
      this.isShowOrderModal = false;
      this.$emit("success");
      this.$emit("close");
    },
    memberRegister() {
      this.$emit("register", this.$refs.memberSearchRef.searchValue);
      this.isShow = false;
      this.$emit("close");
    },
    closeDrawer() {
      this.isShow = false;
      this.$emit("close");
    },
    memberSelect(item) {
      console.log(item, "========88");
      const fn = () => {
        this.memberInfo = item;
        this.$set(this.param, "memberId", item.id);
        this.getPolicyInfo();
        this.androidSelectMember();
        // this.$refs.form.clearValidate()
      };
      fn();
      if (item.cardTypeId && item.cardTypeId !== "") {
        this.$message.warning(this.$t("message.gyhykk"));
      }
    },
    memberClear() {
      this.memberInfo = {};
      this.getPolicyInfo();
      this.androidSelectMember();
    },
    // 安卓选择商品
    androidHandle(e) {
      console.log(e, "===============366");
      let datas = [];
      datas.push({
        title: "会员充值",
        price: e.allPrice,
        num: 1,
        infos: [
          `${this.$t("message.dpice")}:${this.$t("message.rmbfh")}${
            e.allPrice
          }`,
        ],
      });
      let info = { datas };
      console.log(info, "===============3s");
      let obj = JSON.stringify(info);
      if (window.Android) {
        Android.setGoods(obj);
        return;
      }
    },
    // 安卓选择会员
    androidSelectMember() {
      let info = {
        showAvatar:
          this.memberInfo.showFaceUrl || this.memberInfo.showAvatar || "", //头像
        nickName: this.memberInfo.nickName || "", // //昵称
        phone: this.memberInfo.phone || "",
        integral: this.memberInfo.integral || "", // //积分
        totalMoney:
          (this.memberInfo.rechargeMoney + this.memberInfo.giveMoney).toFixed(
            2
          ) || 0, //总金额
      };
      console.log(info, "===============1");
      let obj = JSON.stringify(info);
      if (window.Android) {
        Android.setMember(obj);
        return;
      }
    },
    getCode() {
      if (this.param.phone.length !== 11) {
        this.$message.error(this.$t("message.qsrzedsjh"));
        return;
      }
      sendSMS({ param: { phone: this.param.phone, type: "01" } })
        .then((res) => {
          if (res.errorCode === "000000") {
            setTimeout(() => {
              this.codeDsiabled = true;
              this.codeBtnText = "(60)" + this.$t("message.cxfs");
              this.time = 60;
              const timeInterval = setInterval(() => {
                this.time--;
                this.codeBtnText =
                  "(" + this.time + ")" + this.$t("message.cxfs");
                if (this.time === 0) {
                  clearInterval(timeInterval);
                  this.codeBtnText = this.$t("message.cxfs");
                  this.codeDsiabled = false;
                  console.log("结束");
                }
              }, 1000);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取卡类型列表
    getCardList() {
      cardList({
        pagination: {
          page: 1,
          rows: 1000,
        },
        param: {},
      })
        .then((res) => {
          if (res.errorCode === "000000") {
            res.recordList.forEach((item) => {
              if (item.isnormal !== "1" && item.channel !== "1_0") {
                this.vipTypes.push(item);
              }
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    selectCard(index) {
      this.vipType = index;
      this.$set(this.param, "cardTypeId", this.vipTypes[index]);
      this.getPolicyInfo();
    },
    onSubmit() {
      if (this.vipType >= this.vipTypes.length) {
        this.$message.error(this.$t("message.klxcw"));
        return;
      }
      this.param.cardTypeId = this.vipTypes[this.vipType].id;
      this.param.memberId = this.memberInfo.id;
      console.log(this.param, "param====");
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.xdLoding = true;
          memberAdd({
            param: this.param,
          })
            .then((res) => {
              this.xdLoding = false;
              if (res.errorCode === "000000") {
                this.getOrderMessage(res.record);
              }
            })
            .catch((err) => {
              this.xdLoding = false;
              console.log(err);
            });
        } else {
          return false;
        }
      });
    },
    getOrderMessage(orderId) {
      memberOrderInfo({ param: { orderId } }).then((res) => {
        if (res.errorCode === "000000") {
          const obj = {
            ...res.record.orderInfo,
            cardName: res.record.cardInfo.cardName,
          };
          this.isShowOrderModal = true;
          this.$nextTick(() => {
            this.$refs.child.continuePay(obj, "vipAdd", this.memberInfo);
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.member_info {
  display: flex;
  flex-wrap: wrap;
  background: #f7f7f7;
  border-radius: 2px;
  padding: 16px;
  margin-top: 10px;
  .item {
    width: 50%;
    line-height: 28px;
    height: 28px;
  }
}
.code-style {
  width: 70%;
}
.code-btn-style {
  margin-left: 20px;
}

.card-style {
  width: 158px;
  height: 160px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #d8d8d8;
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 12px;
  line-height: 16px;
  cursor: pointer;
  img {
    width: 134px;
    height: 80px;
    display: flex;
    margin-bottom: 12px;
  }
  .card-name {
    color: #222;
    font-weight: 500;
    line-height: 18px;
    margin-bottom: 10px;
  }
}
.cart_list {
  display: flex;
  flex-wrap: wrap;
}
.select-style {
  border: solid 1px $primaryColor;
}
.base-message-style {
  width: 50%;
  display: inline-block;
  .base-value-style {
    font-size: 13px;
  }
  .card-name-style {
    display: inline-block;
    border: 1px #999 solid;
    border-radius: 4px;
    background-color: #fff;
    font-size: 12px;
    padding-left: 5px;
    padding-right: 5px;
    height: 20px;
    line-height: 20px;
    margin-top: 10px;
    padding-bottom: -15px;
    text-align: center;
  }
}

.btns-style {
  // width: 80%;
  margin-left: 10%;
}
.money-value-style {
  color: #dd0707;
  font-weight: 500;
}

.card-message {
  margin-top: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
.yhzc {
  font-size: 13px;
  line-height: 36px;
  padding: 0 9px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #222222;
  height: 36px;
  background: rgba(238, 56, 33, 0.06);
  margin: 10px 0;

  span {
    color: #ee3821;
  }
}
</style>
